var _callback60 = [];
var _callback30 = [];
var _callback15 = [];
var _count = 0;
var _nextId = 0;
var _tick = 0;
var _pause = false;

/**
 * 用于需要每秒执行若干次的函数
 */

var ret = {
	registUpdate: function(cb, time, front){
		var id = _nextId;
		_nextId += 4;
		var target;
		if(time == 60){
			target = _callback60;
		}else if(time == 30){
			target = _callback30;
			id += 1;
		}else{
			target = _callback15;
			id += 2;
		}
		if(front){
			target.unshift([id, cb]);
		}else{
			target.push([id, cb]);
		}
		_count++;
		if(_count == 1){
			_pause = false;
			this.startPoll();
		}
		return id;
	},

	unregisterUpdate: function(id) {
		var t = id & 3;
		var target;
		switch (id & 3) {
			case 0:
				target = _callback60;
				break;
			case 1:
				target = _callback30;
				break;
			case 2:
				target = _callback15;
				break;
			default:
				return;
		}
		for (var i = target.length - 1; i >= 0; i--) {
			if (target[i][0] == id) {
				target.splice(i);
				if (--_count == 0) {
					this.pause();
				}
				return;
			}
		}
	},

	pause: function(){
		_pause = true;
	},

	resume: function(){
		_pause = false;
		this.startPoll();
	},

	startPoll: function(){
		_tick++;
		for(var i=_callback60.length-1;i>=0;i--){
			_callback60[i][1]();
		}
		if(_tick % 2 == 0){
			for(var i=_callback30.length-1;i>=0;i--){
				_callback30[i][1]();
			}
		}
		if(_tick % 4 == 0){
			for(var i=_callback15.length-1;i>=0;i--){
				_callback15[i][1]();
			}
		}
		if(!_pause){
			setTimeout(this.startPoll.bind(this), 16);
		}
	}
};

module.exports = ret;